<?php
class PostsController extends  Controller{

	public function index(){
		$this->getSmarty();
		$this->smarty->display("admin/posts/posts.tpl");
	}
	 
	/**获取所有文章*/
	public function getAllPosts(){
		$this->getSmarty();
		require_once SERVICE . DS . 'admin/PostsService.class.php';
		// START 数据库查询及分页数据
		$postsService = new PostsService( $this->getDB () );

		//获取所有参数
		$argsArr = $_POST;
		
		
		$page = isset ( $_POST ['page'] ) ? intval ( $_POST ['page'] ) : 1;
		$rows = isset ( $_POST ['rows'] ) ? intval ( $_POST ['rows'] ) : 10;
		$POST_CATEGORY = $argsArr['POST_CATEGORY'];
		$POST_TITLE = $argsArr['POST_TITLE'];
		$POST_STATUS = $argsArr['POST_STATUS']; 
		$condition=$this->getCondition($POST_CATEGORY, $POST_TITLE, $POST_STATUS);
		$offset = ($page - 1) * $rows;
		$result = array ();

		$row_count = $postsService->countNum ($condition);
		$result ["total"] = $row_count;
		$posts = $postsService->postsPage ( $offset, $rows,$condition);
		$items = array ();
		$result ["rows"] = $posts;
		echo json_encode ( $result );
	}
	/**获取文章过滤查询条件*/
	function getCondition($POST_CATEGORY,$POST_TITLE,$POST_STATUS){
		$condition=array();
		if($POST_CATEGORY!=""){
			$condition['POST_CATEGORY']="POST_CATEGORY = '".$POST_CATEGORY."'";
		}
		if($POST_TITLE!=""){
			$condition['POST_TITLE']="POST_TITLE like '%".$POST_TITLE."%'";
		}
		if($POST_STATUS!=""){
			$condition['POST_STATUS']="POST_STATUS = '".$POST_STATUS."'";
		}
		$i=0;
		foreach ($condition as $key => $value){

			if($i==count($condition)-1){
				$conditions.=$value;
			}else{
				$conditions.=$value." and ";
			}
			$i++;
		}
		return $conditions;
	}
	
	/**
	 * 删除文章
	 * Enter description here ...
	 */
	public function removePosts(){
		$this->getSmarty();
		require_once SERVICE . DS . 'admin/PostsService.class.php';
		$id =  $_POST ['ID'];
		$postsService = new PostsService( $this->getDB () );

		$status = $postsService->removePosts ($id);
		if($status=='1'){
			echo json_encode("OK");
		}else {
			echo json_encode("ERROR");
		}
	}
}